package com.example.coursemanagement.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.coursemanagement.MyUtils.CommonResult;
import com.example.coursemanagement.MyUtils.RedisCache;
import com.example.coursemanagement.MyUtils.ResultCode;
import com.example.coursemanagement.mapper.ClassMapper;
import com.example.coursemanagement.mapper.UserMapper;
import com.example.coursemanagement.pojo.Class;
import com.example.coursemanagement.pojo.User;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yangmenghen
 * @since 2020-06-01
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final UserMapper userMapper;
    private final ClassMapper classMapper;

    @Resource
    private RedisCache redisCache;

    @GetMapping("/select")
    public CommonResult<User> queryAllUserById(int id){
        User all = userMapper.selectById(id);
        System.out.println(all);
        return CommonResult.success(all);
    }

    @ApiOperation("查询所有的用户信息")
    @RequestMapping(value = "/selectAll",method = RequestMethod.GET)
    public CommonResult<Object> queryAllUser(){
        Collection<User> users = userMapper.selectList(null);
        if(users==null){
            return CommonResult.failed(ResultCode.FAILED);
        }
        else{
            return CommonResult.success(users);
        }

    }

    @ApiOperation("登录")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public CommonResult<Object> login(@RequestBody User user){
        Map<String,Object> map = new HashMap<>();
        map.put("account",user.getAccount());
        if(userMapper.selectByMap(map).isEmpty()){
            return CommonResult.validateFailed("无用户信息");
        }
        else{
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("account",user.getAccount());
            User user1 = userMapper.selectOne(queryWrapper);
            if(user1.getPassword().equals(user.getPassword())){
                return CommonResult.success(user1,"登录成功");
            }
            else{
                return CommonResult.validateFailed("用户名或密码错误");
            }
//            if(userMapper.login(user).getPassword().equals(user.getPassword())){
//                return CommonResult.success(userMapper.login(user),"登录成功");
//            }
//            else {
//                return CommonResult.validateFailed("用户名或密码错误");
//            }
        }

    }

    @ApiOperation(value = "新增/注册操作")
    @RequestMapping(value = "/addUser",method = RequestMethod.POST)
    public CommonResult<Object> addUser(User user){
        //根据登录账号判断是否是重复账号
        Map<String,Object> map = new HashMap<>();
        map.put("account",user.getAccount());
        System.out.println(userMapper.selectByMap(map));
        System.out.println(userMapper.selectByMap(map));
        if(userMapper.selectByMap(map).isEmpty()){
            if(userMapper.insert(user)>0){
                if(classMapper.selectById(user.getClassId())==null){
                    return CommonResult.validateFailed("输入的班级不存在");
                }
                else{
                    //实现班级人数加一
                    UpdateWrapper<Class> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("id",user.getClassId())
                            .setSql("student_count=student_count+1");
                    classMapper.update(null, updateWrapper);
                }
                return CommonResult.success(ResultCode.ADD_SUCCESS);
            }
            else{
                return CommonResult.failed(ResultCode.FAILED);
            }
        }
        else{
            return CommonResult.validateFailed("该用户已存在");
        }
    }

    @ApiOperation("根据id删除")
    @RequestMapping(value = "/deleteUser",method = RequestMethod.DELETE)
    public CommonResult<Object> deleteUser(int id){
        if(userMapper.deleteById(id)>0){
            return CommonResult.success(ResultCode.DELETE_SUCCESS);
        }
        else{
            return CommonResult.failed(ResultCode.FAILED);
        }
    }

    @ApiOperation(value = "修改操作")
    @RequestMapping(value = "/updateUser",method = RequestMethod.POST)
    public CommonResult<Object> updateUser(@RequestBody  User user){
        if(userMapper.updateById(user)>0){
            //用户信息修改成功后，向Redis中缓存用户信息，如果之后进行消息界面，查询到redis中对应键的值不为空，则说明用户修改了信息，并且未读
            redisCache.setCacheObject("updateSuccess"+user.getId(), user);
            return CommonResult.success(ResultCode.UPDATE_SUCCESS);
        }
        else {
            return CommonResult.failed(ResultCode.FAILED);
        }
    }

    /**
     * 用于检查用户是否修改信息成功，在进入信息界面的时候必须调用
     * @param userId
     * @return
     */
    @RequestMapping(value = "/checkUpdate",method = RequestMethod.GET)
    public CommonResult<Object> checkUpdate(@RequestParam("userId") int userId) {
        User user = redisCache.getCacheObject("updateSuccess"+userId);
        if (Objects.isNull(user)) {
            return CommonResult.failed("用户没有更新信息");
        }
        redisCache.deleteObject("updateSuccess" + userId);
        return CommonResult.success("用户修改信息成功");
    }

    @ApiOperation(value = "管理员登录")
    @PostMapping("/admin")
    public CommonResult<Object> adminLogin(User user){
        if(user != null){
            if (user.getAccount()!=null && user.getAccount().equals("admin")){
                Map<String,Object> map = new HashMap<>();
                map.put("account","admin");
                List<User> list = userMapper.selectByMap(map);
                String pwd = list.get(0).getPassword();
                if(user.getPassword()!=null && user.getPassword().equals(pwd)){
                    return CommonResult.success(userMapper.selectByMap(map).get(0));
                }
            }
        }
        return CommonResult.failed(ResultCode.ACCOUNTORPWDERROR);
    }

    @ApiOperation(value = "根据班级id,查询所有学生")
    @GetMapping("/getStudents")
    public CommonResult<Object> getStudents(int classId){
        List<User> users = userMapper.selectByClassId(classId);
        return CommonResult.success(users);
    }





}


